package com.nanbei.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;

/**
 * @ClassDescription: 线程中断的3种方式
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/27 16:18
 */
public class InterruptAPIDemo {
    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        // 使用volatile 关键字来暂停线程
        // method1();

        // 使用原子类暂停线程
        // method2();

        // 使用interrupt()方法暂停线程
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("main线程请求 t1线程中断");
                    break;
                }
                System.out.println("t1线程正在运行");
            }
        }, "t1");
        thread.start();

        try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(thread::interrupt).start();



    }

    private static void method2() {
        new Thread(()->{
            while (true){
                if (atomicBoolean.get()){
                    System.out.println("atomicBoolean 值被修改为true , t1线程中断");
                    break;
                }
                System.out.println("t1线程正在运行");
                try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        },"t1").start();

        try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(()->{
            atomicBoolean.set(true);
        }).start();
    }

    private static void method1() {
        new Thread(()->{
            while (true){
                if (isStop){
                    System.out.println("isStop 值被修改为true , t1线程中断");
                    break;
                }
                System.out.println("t1线程正在运行");
            }
        },"t1").start();

        try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(()->{
            isStop = true;
        }).start();
    }
}
